﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Serialization;
using ZeroBug.EasyFlow.Core;

namespace ZeroBug.EasyFlow.Communication
{
    public class SendPackage<T>
    {
        [XmlIgnore]
        public bool ReceivingFlag { get; set; }
        public T StartPattern { get; set; }
        public T EndPattern { get; set; }
        public T Message { get; set; }
        [XmlIgnore]
        public T ReceivedData { get; set; }
        [XmlIgnore]
        public Func<T, T> SendRule { get; set; }
        public SendPackage()
        {
            ReceivingFlag = false;
            ReceivedData = default(T);
        }
        public bool Wait(int timeOut, Func<bool> isBreak)
        {
            DateTime startTime = DateTime.Now;
            TimeSpan ts = DateTime.Now - startTime;
            while(!ReceivingFlag && !isBreak.Invoke() && ts.TotalMilliseconds <= timeOut)
            {
                ts = DateTime.Now - startTime;
                Thread.Sleep(2);
            }
            if (ReceivingFlag)
                return true;
            return false;
        }
    }
}
